package struts.core.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

/** 
* @ClassName: StrutsXmlUtil 
* @Description: 解析xml配置文件工具类 
* @author zx zx2009428@163.com
* @date 2014年12月18日 上午10:33:17 
*  
*/
public class StrutsXmlUtil {

	public StrutsXmlUtil() {
	}
	
	public static Map<String,StrutsXMLBean> strtus_xml(String xmlPath) throws Exception, IOException{
		
		Map<String,StrutsXMLBean> map = new HashMap<String,StrutsXMLBean>();
		
		SAXBuilder saxbuilder = new SAXBuilder();
		Document document = saxbuilder.build(new File(xmlPath));
		
		Element root = document.getRootElement();
		
		Element formmap = root.getChild("formbeans");
		List<Element> formbeans = formmap.getChildren();
		Element actionmap = root.getChild("actionmapping");
		List<Element> actions = actionmap.getChildren();
		for(Element action :actions){
			StrutsXMLBean xmlBean = new StrutsXMLBean();
			String actionName  = action.getAttributeValue("name");
			String actionClass = action.getAttributeValue("class");
			String actionPath = action.getAttributeValue("path");
			
			xmlBean.setActionClass(actionClass);
			xmlBean.setActionName(actionName);
			xmlBean.setActionPath(actionPath);
			
			for(Element formbean:formbeans){
				String formbeanName = formbean.getAttributeValue("name");
				if(actionName.equals(formbeanName)){
					String frombeanClass = formbean.getAttributeValue("class");
					xmlBean.setFormbeanClass(frombeanClass);
					xmlBean.setFormbeanName(formbeanName);
					
					break;
				}
			}
			
			List<Element> forwards = action.getChildren();
			Map<String,String> forwardmap = new HashMap<String,String>();
			for(Element forward:forwards){
				String forwardName  = forward.getAttributeValue("name"); 
				String forwardValue = forward.getAttributeValue("value"); 
				forwardmap.put(forwardName, forwardValue);
				xmlBean.setForwards(forwardmap);
			}
			
			map.put(actionPath, xmlBean);
		}
		return map;
	}

}
